var express = require('express');
var router = express.Router();

var { UserModel } = require("../utils/model")

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

// 注册
router.post('/register/submit', (req, res) => {
  var body = req.body;
  UserModel.findOne({
    username: body.username,
  }).then(data => {
    if (data) {
      res.json({
        msg: "用户名已存在",
        code: 200,
        type: 0,
      })
    } else {
      body.time = new Date();
      UserModel.insertMany(body)
        .then(result => {
          res.json({
            msg: "注册成功,即将跳转到登录页",
            code: 200,
            type: 1,
          })
        })
        .catch(err => {
          res.json({
            msg: "注册失败",
            code: 200,
            type: 0,
          })
        })
    }
  })
})

//登录
router.post('/login/submit', (req,res) => {
  var body = req.body;
  UserModel.findOne(body, { _id: 0 })
    .then(result => {
      if (result) {
        // 登录成功
        req.session.username = body.username;

        res.json({
          msg: "登录成功,即将进入首页",
          code: 200,
          result,  // 用户信息 
          type: 1 // 1 成功   
        })
      } else {
        res.json({
          msg: "用户名或者密码不正确,请重新登录",
          code: 200,
          type: 0 // 0 失败 
        })
      }
    })
})

// 注销  
router.get("/logout",(req,res)=>{
  // 销毁session 
    req.session.destroy(()=>{
        res.redirect("/");  // redirect 重定向 
    })
})

module.exports = router;
